import Taro from '@tarojs/taro';
import i18n from 'i18n-js';
import { clearAllPassword } from '@/templates/containers/devicePasswordVerifyModal/passwordStorage';
import SecureStore from './AsyncStorage';
import global from './global';
import Toast from './Toast';
import { StorageWechatUnionidKey, StorageTokenKey, StorageUidKey } from './loginStatus'



// eslint-disable-next-line consistent-return
export async function removeItem(key: string) {
  try {
    return await SecureStore.removeItem(key);
  } catch (error) {
    console.error(error);
  }
}

let logoutLoading = false;

export default async (showTip = true) => {

  if (logoutLoading) {
    // 注销账号的时候，PushManager.deleteAlias又会触发一次logout，这里需要加锁防止多次调用
    return;
  }
  logoutLoading = true;
  global.token = null;
  if (global.cleanData) {
    global.cleanData();
  }
  clearAllPassword();
  await removeItem(StorageUidKey)
  await removeItem(StorageTokenKey)
  await removeItem(StorageWechatUnionidKey)
  // 跳回到首页
  Taro.navigateBack({ delta: 100 });
  if (showTip) {
    Toast.info(i18n.t('LOGIN_INFO_INVALID'));
  }
  logoutLoading = false;
};
